var canvasOri = document.querySelector('.original')
var canvasEdi = document.querySelector('.edited')
var imgData = null
var ctxOri = canvasOri.getContext('2d')
var ctxEdi = canvasEdi.getContext('2d')
var reader = new FileReader()
var img = new Image()
var file = document.querySelector('input')
var dropdown = document.querySelector("select")

//read image data out of the file element
function readImage() {
    reader.onload = function () {
        img.src = this.result
        img.onload = () => {
            ctxOri.drawImage(img, 0, 0)
        }
    }
    reader.readAsDataURL(file.files[0])
}

//B&W effect
function blackAndWhiteEffect(pixels) {
    for (let i = 0; i < pixels.length; i += 4) {
        var avg = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3
        pixels[i] = pixels[i + 1] = pixels[i + 2] = avg > 100 ? 255 : 0
    }
}

//negative effect
function negativeEffect(pixels) {
    for (let i = 0; i < pixels.length; i += 4) {
        pixels[i] = 255 - pixels[i]
        pixels[i + 1] = 255 - pixels[i + 1]
        pixels[i + 2] = 255 - pixels[i + 2]
    }
}

//grey scale effect
function greyScaleEffect(pixels) {
    for (let i = 0; i < pixels.length; i += 4) {
        var avg = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3
        pixels[i] = pixels[i + 1] = pixels[i + 2] = avg
    }
}

//abstract effect
function abstractEffect(pixels) {
    for (let i = 0; i < pixels.length; i += 4) {
        [pixels[i], pixels[i + 1], pixels[i + 2]] = purifyPixel(pixels[i], pixels[i + 1], pixels[i + 2])
    }
}

//converting each pixel to pure red or blue or green
function purifyPixel(r,g,b){
    if(r>=b && r>=g){
       return [255,0,0]
    } else if(b>=r && b>=g){
        return [0,0,255]
    } else {
        return [0,255,0]
    }
}

//process user inputs
function changeEffect(type) {
    //get the original image stored in the first canvas element
    imgData = ctxOri.getImageData(0, 0, canvasOri.width, canvasOri.height)
    //get the array of color information
    var pixels = imgData.data
    if (type == 1) {
        negativeEffect(pixels)
    } else if (type == 2) {
        greyScaleEffect(pixels)
    } else if (type == 3) {
        blackAndWhiteEffect(pixels)
    } else if (type == 4) {
        abstractEffect(pixels)
    }
    ctxEdi.putImageData(imgData, 0, 0)//pour modified pixels into second canvas
}

//listening to user events
file.addEventListener('change', function () {
    readImage()
})

dropdown.addEventListener('change', function () {
    changeEffect(this.value)
})
